package svc

import (
	"fmt"
	"time"

	"diff.wang/asynqsrv/common"
	"diff.wang/asynqsrv/server/internal/config"
	"github.com/hibiken/asynq"
)

type ServiceContext struct {
	Config config.Config

	AsynqServer *asynq.Server
}

func NewServiceContext(c config.Config) *ServiceContext {
	return &ServiceContext{
		Config: c,
		AsynqServer: asynq.NewServer(
			asynq.RedisClientOpt{Addr: c.Redis.Host, Password: c.Redis.Pass, DB: c.RedisDB},
			asynq.Config{
				IsFailure: func(err error) bool {
					fmt.Printf("asynq server exec task failed, err: %+v \n", err)
					return true
				},
				Concurrency: 20, // 最大并发进程作业任务数
				RetryDelayFunc: func(n int, e error, t *asynq.Task) time.Duration {
					if t.Type() == common.MsgEmailDelivery { // 如果是邮件分发，2秒后重试，其他走默认重试
						return 2 * time.Second
					}
					return asynq.DefaultRetryDelayFunc(n, e, t)
				},
			},
		),
	}
}
